cmake_minimum_required(VERSION 3.10)
project(l2fwd LANGUAGES C)

# 检查 pkg-config 是否可用
find_program(PKG_CONFIG pkg-config)
if(NOT PKG_CONFIG)
    message(FATAL_ERROR "pkg-config not found")
endif()

# 检查 DPDK 是否安装
execute_process(
    COMMAND ${PKG_CONFIG} --exists libdpdk
    RESULT_VARIABLE PKG_CONFIG_RESULT
)
if(NOT PKG_CONFIG_RESULT EQUAL 0)
    message(FATAL_ERROR "No installation of DPDK found")
endif()

# 获取 DPDK 的编译和链接标志
execute_process(
    COMMAND ${PKG_CONFIG} --cflags libdpdk
    OUTPUT_VARIABLE DPDK_CFLAGS
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

execute_process(
    COMMAND ${PKG_CONFIG} --libs libdpdk
    OUTPUT_VARIABLE DPDK_LDFLAGS_SHARED
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

execute_process(
    COMMAND ${PKG_CONFIG} --static --libs libdpdk
    OUTPUT_VARIABLE DPDK_LDFLAGS_STATIC
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

# 检查静态链接是否支持
if(CMAKE_BUILD_TYPE STREQUAL "static")
    if(NOT DPDK_LDFLAGS_STATIC MATCHES "whole-archive.*l:lib.*no-whole-archive")
        message(FATAL_ERROR "Cannot generate statically-linked binaries with this version of pkg-config")
    endif()
endif()

# 设置编译标志
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 ${DPDK_CFLAGS} -DALLOW_EXPERIMENTAL_API")

# 源文件
set(SOURCES
    main.c
)

# 创建动态链接的可执行文件
add_executable(${PROJECT_NAME}-shared ${SOURCES})
target_link_libraries(${PROJECT_NAME}-shared PRIVATE ${DPDK_LDFLAGS_SHARED})

# 创建静态链接的可执行文件
add_executable(${PROJECT_NAME}-static ${SOURCES})
target_link_libraries(${PROJECT_NAME}-static PRIVATE ${DPDK_LDFLAGS_STATIC})

# 创建符号链接
add_custom_command(
    TARGET ${PROJECT_NAME}-shared POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E create_symlink "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-shared" "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}"
)

add_custom_command(
    TARGET ${PROJECT_NAME}-static POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E create_symlink "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-static" "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}"
)

# 清理构建目录
add_custom_target(clean-all
    COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_BINARY_DIR}"
)
